import numpy as np
import matplotlib.pyplot as plt
from progressbar import Bar, Percentage, RotatingMarker,ETA, ProgressBar
from matplotlib import colors, ticker

def buildHist(xarr,yarr,xlim,ylim,b=1e2):
    r=[[xlim[0],xlim[1]],[ylim[0],ylim[1]]]
    h = np.zeros((b,b))
    pbar  = ProgressBar(widgets=['Build Histogram: ', Percentage(), ' ', Bar(marker=RotatingMarker()),' ', ETA()],maxval=xarr.shape[0]).start()
    for i in xrange(xarr.shape[0]):
        hist,xedges,yedges=np.histogram2d(xarr[i,:],yarr[i,:],bins=b,range=r)
        h += hist
        pbar.update(i)
    pbar.finish()
    return h, xedges, yedges

def contourPhase(hist,xedges,yedges,show=True,fileName=None):
    #plt.figure(figsize=(5,3),dpi=150)
    #plt.clf()
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1] ]
    lev=np.array([pow(10,i/(19/np.log10(hist.max()))) for i in range(20)])
    plt.contourf(hist.T,interpolation='gaussian',extent=extent,locator=ticker.LogLocator(),levels=lev)
    bar=plt.colorbar()
    tick_locs=[j*pow(10,i) for j in range(10) for i in range(10)]
    tick_locs.sort()
    bar.locator = ticker.FixedLocator(tick_locs)
    bar.update_ticks() 
    for i in bar.ax.get_yticklabels():
        if i.get_text() == '$10^{0}$':
            i.set_text('$1$')
        i.set_fontsize(15.0)
    plt.xlabel('Phase Error [deg at 704MHz]',fontsize=20)
    plt.ylabel('Energy Error [MeV]',fontsize=20)
    plt.xticks(fontsize=15.0)
    plt.yticks(fontsize=15.0)
    if fileName:
        plt.savefig(fileName,dpi=500)
    else:
        if show==True:
            plt.show()

